package com.hellowx.qydcdev.controller;

import com.google.code.kaptcha.Producer;
import com.hellowx.qydcdev.constant.RedisPrefix;
import com.hellowx.qydcdev.utils.ImageUtils;
import com.hellowx.qydcdev.utils.RedisUtils;
import com.hellowx.qydcdev.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Api(tags = "验证码模块")
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {

    @Resource
    private RedisUtils redisUtils;
    @Resource
    private Producer captchaProducer;

    @ApiOperation("获取验证码")
    @GetMapping
    public String getKaptcha(HttpServletRequest request){
        try{
            String ipAddr = UserUtils.getIpAddr(request);

            String text = captchaProducer.createText();
            redisUtils.set(ipAddr + RedisPrefix.CAPTCHA, text, 300L);
            BufferedImage image = captchaProducer.createImage(text);
            return ImageUtils.getBufferedImageToBase64(image, "jpg");
        }catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
